﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using PmSoft.Web.Abstractions.RealTime;
using PmSoft.Core.Domain;

namespace PmSoft.Web.Abstractions.SignalR;

public class OnlineClientInfoProvider : IOnlineClientInfoProvider
{
	private readonly ILogger _logger;
	private readonly IClientInfoProvider _clientInfoProvider;

	public OnlineClientInfoProvider(ILogger<OnlineClientInfoProvider> logger,
		IClientInfoProvider clientInfoProvider)
	{
		_clientInfoProvider = clientInfoProvider;
		_logger = logger;
	}


	public IOnlineClient CreateClientForCurrentConnection(HubCallerContext context)
	{
		var client = new OnlineClient(
			context.ConnectionId,
			GetIpAddressOfClient(context),
			context.GetTenantType(),
			context.GetUserIdOrNull()
		);
		client.Properties["UserAgent"] = _clientInfoProvider.BrowserInfo;
		return client;
	}

	private string GetIpAddressOfClient(HubCallerContext context)
	{
		try
		{
			return _clientInfoProvider.ClientIpAddress;
		}
		catch (Exception ex)
		{
			_logger.LogError("Can not find IP address of the client! connectionId: " + context.ConnectionId);
			_logger.LogError(ex.Message, ex);
			return "";
		}
	}
}
